<template>
	<el-card>
		<!-- <el-form :inline="true" :model="state.queryForm">
			<el-form-item>
				<el-input v-model="state.queryForm.username" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.mobile" placeholder="手机号"></el-input>
			</el-form-item>
			<el-form-item>
				<fast-select v-model="state.queryForm.gender" dict-type="user_gender" clearable placeholder="性别"></fast-select>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item>
			<fast-user @select="userHandle"></fast-user>
			<el-form-item>
				<el-button type="danger" @click="deleteBatchHandle()">删除</el-button>
			</el-form-item>
		</el-form> -->
		<el-space wrap style="margin-bottom: 0;">
			<el-button v-auth="'sys:role:connect:update'" type="primary" @click="update">编辑</el-button>
		</el-space>
		<el-table v-loading="state.dataListLoading" :data="state.dataList" border style="width: 100%"
			@selection-change="selectionChangeHandle" @sort-change="sortChangeHandle">
			<el-table-column prop="id" label="序号" header-align="center" align="center">
				<template #default="scope">
					{{ (state.page - 1) * state.limit + scope.$index + 1 }}
				</template>
			</el-table-column>
			<el-table-column prop="realName" label="姓名" header-align="center" align="center"></el-table-column>
			<el-table-column prop="username" label="用户名" header-align="center" align="center"></el-table-column>
			<el-table-column prop="mobile" label="手机号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="orgName" label="所属机构" header-align="center" align="center"></el-table-column>
			<el-table-column prop="department" label="科室" header-align="center" align="center"></el-table-column>
			<el-table-column prop="createTime" label="加入机构时间" header-align="center" align="center">
				<template #default="scope">
					{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
				<template #default="scope">
					<el-button v-auth="'sys:role:connect:update'" type="primary" link
						@click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination :current-page="state.page" :page-sizes="state.pageSizes" :page-size="state.limit"
			:total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle"
			@current-change="currentChangeHandle">
		</el-pagination>
	</el-card>
	<el-dialog v-model="dialog.visible" width="800px" :title="dialog.title" :close-on-click-modal="false" draggable>
		<el-transfer ref="transfer" class="transfer" v-model="transferValue" filterable :titles="['全部用户', '关联用户']"
			filter-placeholder="请输入姓名/手机号/科室" :data="transferData" :filter-method="transferSearch">
			<template #default="{ option }">
				<span :title="option.label">{{ option.label }}</span>
			</template>
		</el-transfer>
		<template #footer>
			<el-button @click="dialog.visible = false">取消</el-button>
			<el-button type="primary" @click="dialogSave" :loading="dialog.loading">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="SysMenuIndex">
import { useCrud } from '@/hooks'
import { reactive, ref } from 'vue'
import { IHooksOptions } from '@/hooks/interface'
import FastUser from '@/components/fast-user/src/fast-user.vue'
import { useRoleUserSubmitApi } from '@/api/sys/role'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import service from '@/utils/request'
import store from '@/store'
import { parseTime } from '@/utils/tool'

const transfer = ref()
const transferData = ref([])
const transferValue = ref([])
const transferSearch = (query, item) => {
	if (query) {
		return item.label.toLowerCase().includes(query.toLowerCase()) || item.department.toLowerCase().includes(query.toLowerCase())
	} else {
		return true
	}
}
const del = item => {
	ElMessageBox.confirm(`确定要移除关联用户[${item.username}]吗?`, '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const params = {
				roleId: props.roleId,
				userIdList: [item.id]
			}
			service.post('/sys/role/delete/user/delete_role', params).then(res => {
				if (res.code === 0) {
					ElMessage({
						message: '删除成功!',
						type: 'success'
					})
					getDataList()
				} else {
					ElMessage({
						message: res.message,
						type: 'error'
					})
				}
			})
		})
		.catch(() => {
			console.log('取消')
		})
}

const dialog = ref({
	title: '编辑关联用户',
	visible: false,
	loading: false
})

const update = () => {
	getUserAll()
	getRoleUser()
	if (transfer.value) { 
		transfer.value.clearQuery('left') 
		transfer.value.clearQuery('right') 
	}
	dialog.value.visible = true
}

const getUserAll = () => {
	const user = store.userStore.user
	const params = {
		orgId: user.orgId
	}
	service
		.get('/sys/role/user/list', {
			params: params
		})
		.then(res => {
			console.log(res)
			res.data.map(v => {
				v.key = v.id
				v.mobile = v.mobile ? v.mobile : ''
				v.department = v.department ? v.department : '未知科室'
				v.label = v.realName + ' ' + v.mobile + ' ' + v.department
			})
			transferData.value = res.data
			console.log(transferData.value)
		})
}
const getRoleUser = () => {
	const user = store.userStore.user
	const params = {
		orgId: user.orgId,
		roleId: props.roleId
	}
	service
		.get('/sys/role/user/list', {
			params: params
		})
		.then(res => {
			transferValue.value = res.data.map(v => {
				return v.id
			})
		})
}

const dialogSave = () => {
	dialog.value.loading = true
	const params = {
		roleId: props.roleId,
		userIdList: transferValue.value
	}
	service
		.post('/sys/role/user/update_role', params)
		.then(res => {
			console.log(res)
			dialog.value.loading = false
			if (res.code === 0) {
				ElMessage({
					message: '编辑成功!',
					type: 'success'
				})
				getDataList()
				dialog.value.visible = false
			}
		})
		.catch(e => {
			dialog.value.loading = false
		})
}

const props = defineProps({
	roleId: {
		type: Number,
		required: true
	}
})

const state: IHooksOptions = reactive({
	dataListUrl: '/sys/role/user/page',
	deleteUrl: '/sys/role/user/' + props.roleId,
	queryForm: {
		roleId: props.roleId,
		orgId: store.userStore.user.orgId,
		username: '',
		mobile: '',
		gender: ''
	}
})

const userHandle = (userIdList: number[]) => {
	console.log(userIdList)
	useRoleUserSubmitApi(props.roleId, userIdList).then(() => {
		ElMessage.success({
			message: '操作成功',
			duration: 500,
			onClose: () => {
				getDataList()
			}
		})
	})
}

const { getDataList, sizeChangeHandle, selectionChangeHandle, sortChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>

<style lang="scss" scoped>
.transfer :deep(.el-transfer-panel) {
	min-width: 290px;
}

::v-deep .el-transfer-panel__item.el-checkbox {
	margin-right: 0;
}
</style>